// pages/home/orderConfirm/orderConfirm.js
import userIndex  from '../../../api/user';
import orderIndex  from '../../../api/order';
import shopCar  from '../../../api/shopCar';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX:app.globalData.isIphoneX,
    addressInfor:null,
    shopCartList:[],
    couponInforList:[],
    couponInfor:null,
    deliveryFee:'',//配送费
    siContract:false,
    allMoney:0,
    DiscountAmount:0,//优惠金额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that=this
    var shopCartList=wx.getStorageSync('shopCartList')
    // shopCartList=shopCartList.map(res=>{
    //   res.img=res.img[0]
    //   return res
    // })
    this.setData({
      shopCartList:shopCartList
    })
   
    this.getUsefulCoupon()
    // this.getShopCart()
    setTimeout(()=>{
      that.getaddressInfor()
    },500)
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  //获取地址
  getaddressInfor(){
    userIndex.apiUseraddressSetDefualtAddress().then(res=>{
      this.setData({
        addressInfor:res.data
      })
      this.getapiDeliveryFee()
    })
  },
  //获取购物车商品
  //获取购物车列表
  getShopCart(){
    shopCar.apishopCartList().then(res=>{
      this.setData({
        shopCartList:res.data,
      })
    })
  },
  getAddress(){
    wx.navigateTo({
      url: '/pages/user/address/address',
    })
  },
//获取配送费
  getapiDeliveryFee(){
    var opt={
      addressId:this.data.addressInfor.id
    }
    opt.products=this.data.shopCartList.map(res=>{
      var obj={
        carId:res.carId||'',
        productId:res.productId,
        qty:res.num,
        sample:res.type==2?1:0,
        skuId:res.skuId
      }
      return obj
    })
    orderIndex.apiDeliveryFee(opt).then(res=>{
      this.setData({
        deliveryFee:res.data.deliveryFee
      })
      this.getMoney()
    })
  },
  //获取优惠券
  getUsefulCoupon(){
    var productIds=''
    var amount=0
    var shopCartList=wx.getStorageSync('shopCartList')
    var ids=shopCartList.map(res=>{
      amount+=Number(res.price)*Number(res.num)
      return res.productId
    })
    productIds=ids.join(',')
    orderIndex.apiUsefulCoupon({productIds:productIds,amount:amount}).then(res=>{
        if(res.data&&res.data.length>0){
          this.setData({
            couponInforList:res.data
          })
        }
    })
  },
  setContract(){
    this.setData({
      siContract:!this.data.siContract
    })
  },

  orderConfirm(e){
    var that=this
    var type=e.currentTarget.dataset.type
    if(!this.data.siContract){
      wx.showToast({
        title: '请先阅读勾选销售合同',
        icon:'none',
      })
      return false
    }
    if(!this.data.addressInfor){
      wx.showToast({
        title: '请先填写收货地址',
        icon:'none',
      })
      return false
    }
    var opt={
      addressId:this.data.addressInfor.id,
      couponId:this.data.couponInfor?this.data.couponInfor.id:'',
      remark:this.data.remark,
      products:this.data.shopCartList.map(res=>{
        var obj={
          carId:res.carId||'',
          productId:res.productId,
          qty:res.num,
          sample:res.type==2?1:0,
          skuId:res.skuId
        }
        return obj
      })
    }
    wx.requestSubscribeMessage({
      tmplIds: ['YQYSAdPntEm0XJ1pacRJBJpQ38JCmhhCIxHiR02uSg4','zlg9J6os0RCYjQWVrFGXAKuQPVPFCCTmv0yDPun9AZI'],
      complete (complete) {
        console.log(complete,'complete')
        wx.removeStorageSync('shopCartList')
        orderIndex.apiSubmiOrder(opt).then(res=>{
          if(type=='pay'){
            that.submit(res.data.amount,res.data.orderNo)
          }else{
            wx.redirectTo({
              url: `/pages/home/behalfPayment/behalfPayment?amount=${res.data.amount}&orderNo=${res.data.orderNo}&type=share`,
            })
          }
          
        })
      }
    })
    
  },

  submit(amount,orderNo){
    // wx.navigateTo({
    //   url: `/pages/home/payResult/payResult??amount=${this.data.amount}&orderNo=${this.data.orderNo}`,
    // })
    // return false
    wx.showLoading({
      title: '支付中'
    });
    orderIndex.apiSubmiPay({orderNo:orderNo}).then(res=>{
      wx.requestPayment({
        timeStamp:res.data.timeStamp,
        nonceStr:res.data.nonceStr,
        package:res.data.package,
        signType:res.data.signType,
        paySign:res.data.paySign,
        success: (res) => {
          setTimeout(function () {
            wx.hideLoading();
          }, 1500)
          if(res.resultCode==6001){
            wx.showToast({
              title:'取消支付',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            }) 
          }else if(res.resultCode==6002){
          wx.showToast({
            title:'网络连接出错,请检查网络连接后重试',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            }) 
          }else{
           wx.redirectTo({
             url: `/pages/home/payResult/payResult?amount=${amount}&orderNo=${orderNo}`,
           })
          }
        },
        fail: (res) => {
          console.log(res)
          wx.showToast({
            title:"取消支付",
            icon: "none",
            duration:3000
          })
      
        }
      });
    })
  },
  usefulCoupon(){
    var productIds=''
    var shopCartList=wx.getStorageSync('shopCartList')
    var allMoney=0
    var ids=shopCartList.map(res=>{
      console.log(res)
      allMoney+=Number(res.price)*Number(res.num)
      return res.productId
    })
    productIds=ids.join(',')
    wx.navigateTo({
      url: `/pages/home/usefulCoupon/usefulCoupon?productIds=${productIds}&allMoney=${allMoney}`,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(this.data.addressInfor){
      this.getapiDeliveryFee()
    }
    if(this.data.couponInfor){
      console.log(this.data.couponInfor,'this.data.couponInforthis.data.couponInfor')
      this.getMoney()
    }
    
  },
  getMoney(){
    var allMoney=0
    var allPrice=0
    var DiscountAmount=0
    var deliveryFee=this.data.deliveryFee
    var couponInfor=this.data.couponInfor
    var shopCartList=this.data.shopCartList.map(res=>{
      allMoney+=Number(res.price)*Number(res.num)
      allPrice+=Number(res.price)*Number(res.num)
    })
    
    if(couponInfor){
      if(couponInfor.type==1){
        allMoney=allMoney-Number(couponInfor.discountAmount)
      }else if(couponInfor.type==2){
        if(allPrice>=Number(couponInfor.qualifiedAmount)){
          allMoney=allMoney-Number(couponInfor.discountAmount)
        }
      }else if(couponInfor.type==3){
        allMoney=allMoney*(couponInfor.rate/10)
      }
    }
    DiscountAmount=allPrice-allMoney

    allMoney=allMoney+Number(deliveryFee)

    this.setData({
      allMoney:allMoney<=0?0.1:allMoney,
      DiscountAmount:DiscountAmount,
    })
  },
  salesContract(){
    wx.navigateTo({
      url: '/pages/home/salesContract/salesContract',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})